package haoyc.handler;

import haoyc.entity.SimpleMouseEvent;
import haoyc.server.RobotClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;

/**
 * @author Memory
 * @version 1.0
 * @date 2021/11/23
 */

@Slf4j
@ChannelHandler.Sharable
public class MouseEventHandler extends SimpleChannelInboundHandler<SimpleMouseEvent> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SimpleMouseEvent event) throws Exception {
        Robot robot = RobotClient.getRobot();

        int mousebuttonmask = -100;
        try {
            switch (event.getMouseId()) {
                case MouseEvent.MOUSE_MOVED:
                case MouseEvent.MOUSE_DRAGGED:
                    robot.mouseMove(event.getX(), event.getY());
                    break;
                case MouseEvent.MOUSE_PRESSED:
                    robot.mouseMove(event.getX(), event.getY());
                    mousebuttonmask = getMouseClick(event.getButton());
                    if (mousebuttonmask != -100) {
                        robot.mousePress(mousebuttonmask);
                    }
                    break;
                case MouseEvent.MOUSE_RELEASED:
                    robot.mouseMove(event.getX(), event.getY());
                    mousebuttonmask = getMouseClick(event.getButton());
                    if (mousebuttonmask != -100) {
                        robot.mouseRelease(mousebuttonmask);
                    }
                    break;
                case MouseEvent.MOUSE_WHEEL:
                    robot.mouseWheel(event.getWheelRotation());
                    break;
                default:
                    log.info("Mouse can't understand");
                    System.out.println(event.getMouseId());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage(), cause);
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        super.channelReadComplete(ctx);
    }


    private int getMouseClick(int button) {
        if (button == MouseEvent.BUTTON1) {
            return InputEvent.BUTTON1_MASK;
        }
        if (button == MouseEvent.BUTTON3) {
            return InputEvent.BUTTON3_MASK;
        }
        return -100;
    }
}
